package com.scjp_Java6.String;

import java.lang.reflect.Field;

/**
 * Just some String examples.
 * 
 * @author Ioana Sebestyen
 */
public class StringTests {

	/**
	 * Shows the usage of some String methods.
	 */
	public void stringMethodsExample() {
		System.out.println("\n== Running the String methods example. ==");
		String s = "    Hello   ";
		s = s.concat(" World! ");
		s = s.replaceAll("\\s+", "-").trim();
		s.toUpperCase();
		System.out.println(s);
	}

	/**
	 * Shows a way to gain access to the inner representation of a String.
	 */
	public void refrectiveAccessExample() {
		System.out.println("\n== Running the reflective access example. ==");
		String s = "Hello World";
		String substring1 = s.substring(0, 5);
		String substring2 = s.substring(6);
		Field valueField;

		try {
			valueField = String.class.getDeclaredField("value");
			valueField.setAccessible(true);
			char[] valueOfSubstring1 = (char[]) valueField.get(substring1);
			char[] valueOfSubstring2 = (char[]) valueField.get(substring2);

			// Have fun with Java 6 and Java 7 :)
			System.out.println("Internal value of substring1 is: "
					+ new String(valueOfSubstring1));
			System.out.println("Internal value of substring2 is: "
					+ new String(valueOfSubstring2));

		} catch (NoSuchFieldException e) {
			e.printStackTrace();
		} catch (SecurityException e) {
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		}
	}

	/**
	 * Some initialisation examples.
	 */
	public void initializationExample() {
		System.out.println("\n== Running the initialization example. ==");
		String emptyString = new String();
		String s = "abc";
		String s2 = s;
		String s3 = new String(s2);
		System.out.println("Is emptyString null? " + (emptyString == null));
		System.out.println("s == s2 ? " + (s == s2));
		System.out.println("s == s3 ? " + (s == s3));
	}

	/**
	 * StringBuilder example. StringBuffer is similar.
	 */
	public void stringBuilderExample() {
		System.out.println("\n== Running the StringBuilder example. ==");
		StringBuilder stringBuilder = new StringBuilder();
		stringBuilder.append("abc").append("DEF");

		System.out.println("System.out.println(stringBuilder) --> "
				+ stringBuilder);
		System.out.println("System.out.println(stringBuilder.toString()) --> "
				+ stringBuilder.toString());
	}

	/**
	 * Entry point of the application.
	 * 
	 * @param args
	 *            Command line arguments.
	 */
	public static void main(String[] args) {
		StringTests stringTests = new StringTests();
		stringTests.initializationExample();
		stringTests.stringMethodsExample();
		stringTests.refrectiveAccessExample();
		stringTests.stringBuilderExample();
	}
}
